#include "userinfowidget.h"
#include "errorhandler.h"
#include <QApplication>
#include <QStyle>
#include <QRegularExpression>

UserInfoWidget::UserInfoWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_userInfoGroup(nullptr)
    , m_formLayout(nullptr)
    , m_usernameEdit(nullptr)

    , m_userIdLabel(nullptr)
    , m_registrationLabel(nullptr)
    , m_lastLoginLabel(nullptr)
    , m_actionGroup(nullptr)
    , m_actionLayout(nullptr)

    , m_changePasswordButton(nullptr)
    , m_refreshButton(nullptr)
    // , m_statusLabel(nullptr)  // 已删除状态标签
    , m_userManager(nullptr)
    , m_isInitialized(false)
{
    // 获取UserManager实例
    m_userManager = &UserManager::instance();
    
    // 初始化界面
    initializeUI();
    
    // 连接UserManager信号
    connect(m_userManager, &UserManager::passwordChanged, this, &UserInfoWidget::onPasswordChanged);
    
    m_isInitialized = true;
}

UserInfoWidget::~UserInfoWidget()
{
    // Qt会自动清理子对象
}

void UserInfoWidget::setUserInfo(const Customer& customer)
{
    m_currentCustomer = customer;
    
    // 更新界面显示
    m_usernameEdit->setText(customer.username);
    m_userIdLabel->setText(customer.id);
    m_registrationLabel->setText(formatDateTime(customer.registrationDate));
    m_lastLoginLabel->setText(formatDateTime(customer.lastLoginDate));
    
    updateUIState();
}

void UserInfoWidget::refreshUserInfo()
{
    if (m_currentCustomer.id.isEmpty()) {
        return;
    }
    
    // 从UserManager获取最新的用户信息
    Customer updatedCustomer = m_userManager->getUserById(m_currentCustomer.id);
    if (!updatedCustomer.id.isEmpty()) {
        setUserInfo(updatedCustomer);
        showOperationResult("用户信息已刷新");
    } else {
        showOperationResult("刷新用户信息失败", false);
    }
}



void UserInfoWidget::clearInputs()
{
    m_usernameEdit->clear();
    m_userIdLabel->clear();
    m_registrationLabel->clear();
    m_lastLoginLabel->clear();
    
    m_currentCustomer = Customer();
}



void UserInfoWidget::onPasswordChanged()
{
    showOperationResult("密码修改成功");
}

void UserInfoWidget::onOperationError(const QString& errorMessage)
{
    showOperationResult(errorMessage, false);
}



void UserInfoWidget::onChangePasswordClicked()
{
    bool ok;
    QString oldPassword = QInputDialog::getText(this, "修改密码", 
                                               "请输入当前密码:", 
                                               QLineEdit::Password, "", &ok);
    
    if (!ok || oldPassword.isEmpty()) {
        return;
    }
    
    // 立即验证原密码是否正确
    if (!m_userManager->verifyCurrentUserPassword(m_currentCustomer.id, oldPassword)) {
        showOperationResult("原密码错误，请重新输入", false);
        return;
    }
    
    QString newPassword = QInputDialog::getText(this, "修改密码", 
                                               "请输入新密码:", 
                                               QLineEdit::Password, "", &ok);
    
    if (!ok || newPassword.isEmpty()) {
        return;
    }
    
    QString confirmPassword = QInputDialog::getText(this, "修改密码", 
                                                   "请再次输入新密码:", 
                                                   QLineEdit::Password, "", &ok);
    
    if (!ok || confirmPassword.isEmpty()) {
        return;
    }
    
    if (newPassword != confirmPassword) {
        showOperationResult("两次输入的密码不一致", false);
        return;
    }
    
    // 验证密码强度
    if (!m_userManager->validatePasswordStrength(newPassword)) {
        showOperationResult("新密码强度不足，请使用至少6位字符，包含字母和数字", false);
        return;
    }
    
    // 发射密码修改请求信号
    emit passwordChangeRequested(oldPassword, newPassword);
}

void UserInfoWidget::onRefreshButtonClicked()
{
    refreshUserInfo();
}



void UserInfoWidget::initializeUI()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(20, 20, 20, 20);
    m_mainLayout->setSpacing(20);
    
    // 创建各个区域
    createUserInfoArea();
    createActionArea();
    
    // 状态标签已删除
    // m_statusLabel = new QLabel(this);
    // m_statusLabel->setAlignment(Qt::AlignCenter);
    // m_statusLabel->setVisible(false);
    // m_mainLayout->addWidget(m_statusLabel);
    
    // 添加弹性空间
    m_mainLayout->addStretch();
    
    // 应用样式
    applyStyleSheet();
    
    // 初始状态设置已移除
}

void UserInfoWidget::createUserInfoArea()
{
    // 创建用户信息分组
    m_userInfoGroup = new QGroupBox("用户信息", this);
    m_formLayout = new QFormLayout(m_userInfoGroup);
    m_formLayout->setLabelAlignment(Qt::AlignRight | Qt::AlignVCenter);
    m_formLayout->setFormAlignment(Qt::AlignLeft | Qt::AlignTop);
    m_formLayout->setSpacing(15);
    
    // 用户ID（只读）
    m_userIdLabel = new QLabel(this);
    m_userIdLabel->setStyleSheet("color: #666; font-family: 'Courier New', monospace;");
    m_formLayout->addRow("用户ID:", m_userIdLabel);
    
    // 用户名
    m_usernameEdit = new QLineEdit(this);
    m_usernameEdit->setMaxLength(50);
    m_usernameEdit->setPlaceholderText("用户名不可修改");
    m_usernameEdit->setReadOnly(true);  // 用户名永远不可编辑
    m_usernameEdit->setStyleSheet("QLineEdit[readOnly=\"true\"] { background-color: #f5f5f5; color: #666; }");
    m_formLayout->addRow("用户名:", m_usernameEdit);
    
    // 注册时间（只读）
    m_registrationLabel = new QLabel(this);
    m_registrationLabel->setStyleSheet("color: #666;");
    m_formLayout->addRow("注册时间:", m_registrationLabel);
    
    // 最后登录时间（只读）
    m_lastLoginLabel = new QLabel(this);
    m_lastLoginLabel->setStyleSheet("color: #666;");
    m_formLayout->addRow("最后登录:", m_lastLoginLabel);
    
    m_mainLayout->addWidget(m_userInfoGroup);
}

void UserInfoWidget::createActionArea()
{
    // 创建操作按钮分组
    m_actionGroup = new QGroupBox("操作", this);
    m_actionLayout = new QHBoxLayout(m_actionGroup);
    m_actionLayout->setSpacing(10);
    
    // 修改密码按钮
    m_changePasswordButton = new QPushButton("修改密码", this);
    m_changePasswordButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_ComputerIcon));
    connect(m_changePasswordButton, &QPushButton::clicked, this, &UserInfoWidget::onChangePasswordClicked);
    m_actionLayout->addWidget(m_changePasswordButton);
    
    // 刷新按钮
    m_refreshButton = new QPushButton("刷新", this);
    m_refreshButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_BrowserReload));
    connect(m_refreshButton, &QPushButton::clicked, this, &UserInfoWidget::onRefreshButtonClicked);
    m_actionLayout->addWidget(m_refreshButton);
    
    // 添加弹性空间
    m_actionLayout->addStretch();
    
    m_mainLayout->addWidget(m_actionGroup);
}

void UserInfoWidget::applyStyleSheet()
{
    // 为1024*600分辨率优化的样式
    setStyleSheet(R"(
        QGroupBox {
            font-size: 14px;
            font-weight: bold;
            color: #333;
            border: 2px solid #ddd;
            border-radius: 8px;
            margin-top: 10px;
            padding-top: 10px;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 15px;
            padding: 0 8px 0 8px;
            background-color: white;
        }
        
        QLineEdit {
            padding: 8px;
            border: 2px solid #ddd;
            border-radius: 4px;
            font-size: 13px;
            background-color: white;
        }
        
        QLineEdit:focus {
            border-color: #4CAF50;
        }
        
        QLineEdit:read-only {
            background-color: #f5f5f5;
            color: #666;
        }
        
        QPushButton {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            font-size: 13px;
            font-weight: bold;
            min-width: 80px;
        }
        
        QPushButton:hover {
            background-color: #2980B9;
        }
        
        QPushButton:pressed {
            background-color: #21618C;
        }
        
        #refreshButton {
            background-color: #2196F3;
            color: white;
        }
        
        #refreshButton:hover {
            background-color: #1976D2;
        }
        
        #changePasswordButton {
            background-color: #FF9800;
            color: white;
        }
        
        #changePasswordButton:hover {
            background-color: #F57C00;
        }
        
        QLabel {
            font-size: 13px;
            color: #333;
        }
        
        .status-success {
            color: #4CAF50;
            font-weight: bold;
            background-color: #E8F5E8;
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #4CAF50;
        }
        
        .status-error {
            color: #f44336;
            font-weight: bold;
            background-color: #FFEBEE;
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #f44336;
        }
    )");
    
    // 设置按钮ID以应用特定样式
    m_changePasswordButton->setObjectName("changePasswordButton");
    m_refreshButton->setObjectName("refreshButton");
}

void UserInfoWidget::updateUIState()
{
    // 根据当前状态更新界面
    bool hasValidUser = !m_currentCustomer.id.isEmpty();
    
    // 启用/禁用控件
    m_userInfoGroup->setEnabled(hasValidUser);
    m_actionGroup->setEnabled(hasValidUser);
    
    // 状态标签已删除
    // if (!hasValidUser) {
    //     m_statusLabel->setText("请先选择用户");
    //     m_statusLabel->setProperty("class", "status-error");
    //     m_statusLabel->setVisible(true);
    // }
}



void UserInfoWidget::showOperationResult(const QString& message, bool success)
{
    // 改为对话框弹出
    if (success) {
        QMessageBox::information(this, "操作成功", message);
    } else {
        QMessageBox::warning(this, "操作失败", message);
    }
}



QString UserInfoWidget::formatDateTime(const QDateTime& dateTime) const
{
    if (!dateTime.isValid()) {
        return "未知";
    }
    return dateTime.toString("yyyy-MM-dd hh:mm:ss");
}
